const express = require("express")
const cors = require("cors")
const bodyParser = require("body-parser")
const jwt = require("jsonwebtoken")
const expressJWT = require('express-jwt')
const mysql = require('mysql')
const jsSHA = require("jssha")
const db = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'shop'
})
const app = express()
// 定义secret秘钥
const secretKey = 'anyString__++'

app.use(cors())
// 配置express-jwt后 自动将解析出来的信息挂载到req.user上
app.use(expressJWT({
  secret: secretKey  // 签名的密钥 或 PublicKey
}).unless({
  path: [/^\/api\//]  // 指定路径不经过 Token 解析
}))
app.use(bodyParser.urlencoded({extended: false}))

app.post('/api/login', (req, res) => {
  const sqlStr = 'select count(*) as total from shop_admin where name=? and password=?'
  // 将传过来的密码转为sha-1加密的哈希值 因为数据库中的也是sha-1加密
  const shaObj = new jsSHA("SHA-1", "TEXT", {encoding: "UTF8"})
  shaObj.update(req.body.password)
  const passwordSha = shaObj.getHash("HEX")
  // 查询数据库
  db.query(sqlStr, [req.body.username, passwordSha], (err, results) => {
    if (err) {
      console.log(err.message)
    } else if (results[0].total > 0) {
      // 生成JWT字符串
      // 用户信息对象 加密秘钥 配置信息
      const token = 'Bearer ' +  jwt.sign({username: req.body.username}, secretKey, {expiresIn: '30min'})
      // 响应客户端
      res.send({
        status: 1,
        code: 200,
        msg: '登陆成功',
        data: {
          token,
        }
      })
      console.log('登陆成功')
    } else {
      res.send('登录失败')
      console.log('登录失败')
    }
  })
})

app.get('/admin/userList', (req, res) => {
  const sqlStr = 'select * from shop_admin'
  db.query(sqlStr, (err, results) => {
    if (err) {
      console.log(err)
    } else if (results.length > 0) {
      res.send({
        status: 1,
        code: 200,
        msg: '成功',
        data: results
      })
    }
  })
})

// 错误处理中间件
app.use((err, req, res, next) => {
  if(err.name === 'UnauthorizedError') {
    // token 解析失败
    return res.send({
      status: 401,
      msg: '无效token'
    })
  }

  res.send({
    status: 401,
    msg: '位置错误'
  })
  next()
})

app.listen(8088, () => {
  console.log('running')
})
